package com.mzlalal.mybatis.interceptor;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.mzlalal.mybatis.interceptor.mybatis.MyTenantLineHandler;
import com.mzlalal.mybatis.interceptor.prop.MyBatisPlusProperties;
import com.mzlalal.mybatis.interceptor.util.TenantIdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 创建模板bean
 * 必须制定模板加载模式,否则不进行服务加载
 *
 * @author Mzlalal
 * @date 2021/4/15 11:03
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(MyBatisPlusProperties.class)
public class MyBatisPlusAutoConfig implements WebMvcConfigurer {

    /**
     * 获取tenantId工具
     *
     * @param myBatisPlusProperties 租户属性配置
     * @return TenantIdService
     */
    @Bean
    public TenantIdService tenantIdService(MyBatisPlusProperties myBatisPlusProperties) {
        return new TenantIdService(myBatisPlusProperties);
    }

    /**
     * 如果没有配置MybatisPlusInterceptor
     * 那么就新建一个MybatisPlusInterceptor并且加入其中
     *
     * @param myBatisPlusProperties 租户属性配置
     * @return MybatisPlusInterceptor
     */
    @Bean
    @ConditionalOnProperty(value = "mz.mybatis.interceptor.enable-tenant-mode", havingValue = "true")
    @ConditionalOnMissingBean(MybatisPlusInterceptor.class)
    public MybatisPlusInterceptor mybatisPlusInterceptor(MyBatisPlusProperties myBatisPlusProperties
            , TenantIdService tenantIdService) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(
                new MyTenantLineHandler(myBatisPlusProperties, tenantIdService)));
        return interceptor;
    }

    /**
     * 如果配置了MybatisPlusInterceptor
     * 那么就追加租户配置
     *
     * @param myBatisPlusProperties 租户属性配置
     * @return MybatisPlusInterceptor
     */
    @Bean
    @ConditionalOnProperty(value = "mz.mybatis.interceptor.enable-tenant-mode", havingValue = "true")
    @ConditionalOnBean(MybatisPlusInterceptor.class)
    public MybatisPlusInterceptor mybatisPlusInterceptor(MybatisPlusInterceptor interceptor
            , MyBatisPlusProperties myBatisPlusProperties, TenantIdService tenantIdService) {
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new MyTenantLineHandler(myBatisPlusProperties, tenantIdService)));
        return interceptor;
    }
}
